package com.zhb86.kuaipai.ui.home;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.google.android.material.tabs.TabLayout;
import com.superyee.commonlib.ui.BaseFragment;
import com.superyee.commonlib.utils.Tag;
import com.superyee.commonlib.videoplayer.cache.PreloadManager;
import com.superyee.commonlib.videoplayer.cache.ProxyVideoCacheManager;
import com.zhb86.kuaipai.R;
import com.zhb86.live.ui.LivePlayer;
import com.zhb86.live.ui.LivePlayerHomeActiviy;

/**
 * 首页tab
 */
public class FTabHome extends BaseFragment {


    private TabLayout tabLayout;
    private ImageButton btnSearch;
    private ImageButton btnLive;
    private ViewPager viewPager;


    public FTabHome() {
        // Required empty public constructor
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_home;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //清除保存的fragment 避免恢复的fragment导致无法播放
            clearSavedInstanceState();
        }
        tabLayout = view.findViewById(R.id.tabLayout);
        btnSearch = view.findViewById(R.id.btnSearch);
        btnLive = view.findViewById(R.id.btnLive);
        viewPager = view.findViewById(R.id.viewPager);
        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @Override
            public int getCount() {
                return 2;
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                if (position == 0) {
                    return new FFollow();
                } else {
                    return new FRecommend();
                }
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                if (position == 0) {
                    return "关注";
                } else {
                    return "推荐";
                }
            }
        });
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(1);
        btnLive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(baseActivity, LivePlayerHomeActiviy.class);
                startActivity(intent);
            }
        });
    }

    private void clearSavedInstanceState() {
        try {
            FragmentManager fm = getChildFragmentManager();
            if (fm != null && fm.getFragments() != null && fm.getFragments().size() > 0) {
                FragmentTransaction ft = fm.beginTransaction();
                for (Fragment fragment : fm.getFragments()) {
                    ft.remove(fragment);
                }
                ft.commitAllowingStateLoss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initData() {

    }

    @Override
    protected void addListener() {

    }

    @Override
    protected void removeListener() {

    }

    @Override
    public void onReceiverNotify(int action, Object obj, int statusCode) {

    }


    @Override
    public void onResume() {
        super.onResume();
        if (isHidden() || !getUserVisibleHint()) {
            return;
        }
        VideoView videoView = getCurrentVideoView();
        if (videoView != null) {
            videoView.resume();
        }
    }

    private VideoView getCurrentVideoView() {
        if(viewPager == null){
            return null;
        }
        if (viewPager.getCurrentItem() == 0) {
            return VideoViewManager.instance().get(Tag.FOLLOW);
        } else {
            return VideoViewManager.instance().get(Tag.RECOMMEND);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        VideoView videoView = getCurrentVideoView();
        if (videoView != null) {
            videoView.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        VideoViewManager.instance().releaseByTag(Tag.FOLLOW, true);
        VideoViewManager.instance().releaseByTag(Tag.RECOMMEND, true);
        PreloadManager.getInstance(baseActivity).removeAllPreloadTask();
        //清除缓存，实际使用可以不需要清除，这里为了方便测试
        ProxyVideoCacheManager.clearAllCache(baseActivity);
    }

    /**
     * fragmentmanager hide  or  show时候调用该方法
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        VideoView videoView = getCurrentVideoView();
        if(videoView == null){
            return;
        }
        if (hidden) {
            videoView.pause();
        } else {
            videoView.resume();
        }
    }


}
